package com.uduemc.biso.node.web.api.controller;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.uduemc.biso.core.extities.node.custom.LoginNode;
import com.uduemc.biso.core.extities.node.custom.LoginNodeAgent;
import com.uduemc.biso.core.utils.JsonResult;
import com.uduemc.biso.node.web.api.component.RequestHolder;
import com.uduemc.biso.node.web.api.exception.NotFoundException;
import com.uduemc.biso.node.web.api.pojo.ResponseAgentInfo;

import cn.hutool.core.util.StrUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

@RestController
@RequestMapping("/api/agent")
@Api(tags = "代理商模块")
public class AgentController {

//	private final static Logger logger = LoggerFactory.getLogger(AgentController.class);

	@Autowired
	private RequestHolder requestHolder;

	@PostMapping("/info")
	@ApiOperation(value = "代理商信息", notes = "获取登录给与的代理商数据信息", response = ResponseAgentInfo.class)
	public JsonResult info() throws JsonParseException, JsonMappingException, JsonProcessingException, IOException {
		LoginNode loginNode = requestHolder.getCurrentLoginNode();
		LoginNodeAgent loginNodeAgent = loginNode.getLoginNodeAgent();
		ResponseAgentInfo rsp = new ResponseAgentInfo();
		rsp.setLoginAgentDomain(loginNodeAgent.getLoginAgentDomain()).setTitle(loginNodeAgent.getTitle());

		String jsessionid = requestHolder.getJsessionid();
		rsp.setFaviconImgSrc("/api/agent/favicon.ico?jsessionid=" + jsessionid);
		rsp.setBackendLogoImgSrc("/api/agent/backend-logo-img.jpg?jsessionid=" + jsessionid);
		rsp.setDesignLogoImgSrc("/api/agent/design-logo-img.jpg?jsessionid=" + jsessionid);

		return JsonResult.ok(rsp);
	}

	@GetMapping("/favicon.ico")
	public void favicon(HttpServletResponse response) throws JsonParseException, JsonMappingException, JsonProcessingException, IOException, NotFoundException {
		LoginNode loginNode = requestHolder.getCurrentLoginNode();
		LoginNodeAgent loginNodeAgent = loginNode.getLoginNodeAgent();
		String faviconImgSrc = loginNodeAgent.getFaviconImgSrc();
		if (StrUtil.isBlank(faviconImgSrc)) {
			throw new NotFoundException("找不到 faviconImgSrc 数据！");
		}

		rspOnlineImg(faviconImgSrc, response, "image/x-icon", 60 * 24);
	}

	@GetMapping("/backend-logo-img.jpg")
	public void backendLogoImgSrc(HttpServletResponse response)
			throws JsonParseException, JsonMappingException, JsonProcessingException, IOException, NotFoundException {
		LoginNode loginNode = requestHolder.getCurrentLoginNode();
		LoginNodeAgent loginNodeAgent = loginNode.getLoginNodeAgent();
		String imgSrc = loginNodeAgent.getBackendLogoImgSrc();
		if (StrUtil.isBlank(imgSrc)) {
			throw new NotFoundException("找不到 faviconImgSrc 数据！");
		}
		rspOnlineImg(imgSrc, response, "image/jpeg; charset=utf-8", 60 * 24);
	}

	@GetMapping("/design-logo-img.jpg")
	public void designLogoImgSrc(HttpServletResponse response)
			throws JsonParseException, JsonMappingException, JsonProcessingException, IOException, NotFoundException {
		LoginNode loginNode = requestHolder.getCurrentLoginNode();
		LoginNodeAgent loginNodeAgent = loginNode.getLoginNodeAgent();
		String imgSrc = loginNodeAgent.getDesignLogoImgSrc();
		if (StrUtil.isBlank(imgSrc)) {
			throw new NotFoundException("找不到 faviconImgSrc 数据！");
		}
		rspOnlineImg(imgSrc, response, "image/jpeg; charset=utf-8", 60 * 24);
	}

	private void rspOnlineImg(String imgSrc, HttpServletResponse response, String contentType, long time) throws IOException, NotFoundException {
		response.setDateHeader("expires", System.currentTimeMillis() + (1000 * time));
		response.setContentType(contentType);
		URL url = new URL(imgSrc);
		HttpURLConnection urlCon = (HttpURLConnection) url.openConnection();
		if (urlCon.getResponseCode() != 200) {
			throw new NotFoundException("找不到 imgSrc 数据！");
		}
		try (ServletOutputStream outputStream = response.getOutputStream(); InputStream is = urlCon.getInputStream();) {
			byte[] buffer = new byte[1024];
			int len = 0;
			while ((len = is.read(buffer)) > 0) {
				outputStream.write(buffer, 0, len);
			}
			outputStream.flush();
		} catch (Exception e) {
			throw new NotFoundException("找不到 imgSrc 数据！");
		}
	}
}
